import Taro, { Component } from '@tarojs/taro'
import { View, Input, Textarea, Switch } from '@tarojs/components'
import Address from '../../../components/address';
import classnames from 'classnames';
import NavigationBar from '../../../components/navigationBar/index';

import './index.scss'
import { createAddress, addressDetail, delAddress, editAddress } from '../../../services/address';
import { isPhoneNumber } from '../../../utils/utils';


export default class EditAddress extends Component {

  config = {
    navigationBarTitleText: '',
  }

  state = {
    form: {},
    id: '',
    isSelected: false,
    list: [],
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
  };


  constructor(props) {
    super(props);
    this.state.id = Number(this.$router.params.id || 0);
  }

  componentDidMount() {
    if (this.state.id) {
      Taro.setNavigationBarTitle({
        title: '修改收货地址'
      })
      addressDetail({
        id: this.state.id
      }).then(res => {
        this.setState({
          form: {
            city: res.city,
            city_name: res.city_name,
            province: res.province,
            province_name: res.province_name,
            region: res.region,
            region_name: res.region_name,
            receiver: res.receiver,
            mobile: res.mobile,
            dft: res.dft,
            address: res.address,
            id: res.id,
          }
        })
      })
    } else {
      Taro.setNavigationBarTitle({
        title: '新建收货地址'
      })
      // setTimeout(() => {
      //   this.setState({
      //     form: {
      //       city:264,
      //       city_name:"晋城市",
      //       province:220,
      //       province_name:"山西省",
      //       region:269,
      //       region_name:"泽州县",
      //       receiver: '123',
      //       mobile: '13412341234',
      //       address: '123',
      //     },
      //     list: [{
      //       id: 220,
      //       region_name: '山西省'
      //     }, {
      //       id: 264,
      //       region_name: '晋城市'
      //     }, {
      //       id: 269,
      //       region_name: '泽州县'
      //     }]
      //   })
      // }, 1000);
    }
  }

  handleText = (key, e) => {
    const { form } = this.state;
    form[key] = e.target.value;
    if (key === 'dft') {
      form[key] = e.target.value ? 1 : 0
    }
    this.setState({
      form,
    })
  }

  save = () => {
    console.log('save', this.state.form);
    if (!isPhoneNumber(this.state.form.mobile)) {
      Taro.showToast({
        title: '手机号码有误',
        icon: 'none'
      });
      return;
    }
    if (!this.state.form.receiver || !this.state.form.address || !this.state.form.region) {
      Taro.showToast({
        title: '请填写信息',
        icon: 'none'
      });
      return;
    }
    if (this.$router.params.id) {
      editAddress({ ...this.state.form }).then(res => {
        Taro.showToast({
          title: '修改成功',
          icon: 'none'
        });
        setTimeout(() => {
          Taro.navigateBack()
        }, 2000);
      })
    } else {
      createAddress({...this.state.form}).then(res => {
        Taro.showToast({
          title: '创建成功',
          icon: 'none'
        });
        setTimeout(() => {
          Taro.navigateBack()
        }, 2000);
      })
    }
  }

  del = () => {
    let that = this;
    Taro.showModal({
      title: '提示',
      content: '你确定删除这个收货地址吗',
      success: function(res) {
        if (res.confirm) {
          delAddress({
            id: that.$router.params.id
          }).then(res => {
            Taro.redirectTo({
              url: '/subPackageWork/pages/my-address/index'
            })
          })
        }
      }
    })
  }

  selectAddress = async () => {
    this.setState({
      isSelected: true
    })
  }

  closeItem = (from) => {
    console.log(from)
    this.setState({
      form: {
        ...this.state.form,
        ...from
      },
      list: []
    })
    this.setState({
      isSelected: false
    })
  }

  render () {
    const { form, id, isSelected, list } = this.state;
    return (
      <View className='edit-address' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text={id ? '编辑收货地址' : '新建收货地址'} />
        <View className="formitem">
          <View className="label">
            收货人
          </View>
          <Input className="input-item" placeholder-class="phcolor" value={form.receiver} onInput={(e) => this.handleText('receiver', e)} placeholder="请填写收货人姓名" />
        </View>
        <View className="formitem">
          <View className="label">
            手机号
          </View>
          <Input className="input-item" placeholder-class="phcolor" value={form.mobile} onInput={(e) => this.handleText('mobile', e)} type="number" placeholder="请填写收货人手机号" />
        </View>
        <View className="formitem">
          <View className="label">
            收货地址
          </View>
          <View className="tip" onClick={this.selectAddress} className={classnames({
            'tip': true,
            'tips': form.province
          })}>
            {
              form.province ? `${form.province_name}${form.city_name || ''}${form.region_name || ''}` : '请选择'
            }
          </View>
        </View>
        <View className="formitem address">
          <View className="label">
            详细地址
          </View>
          {!isSelected && <Textarea className="text-item"  value={form.address} onInput={(e) => this.handleText('address', e)} placeholder="街道、楼牌号等" />}
        </View>
        <View className="formitem default">
          <View className="label">
            设置默认地址
          </View>
          <Switch checked={form.dft} className="switch" color="#000000" onChange={(e) => this.handleText('dft', e)} />
        </View>
        {
          id ? (
            <View className="btn-box">
              <View className="delete-btn" onClick={this.del}>删除</View>
              <View className="save-btns" onClick={this.save}>保存</View>
            </View>
          ) : <View className="save-btn" onClick={this.save}>保存</View>
        }
        <Address isSelected={isSelected} defaultvalue={list} closeItem={this.closeItem} />
      </View>
    )
  }
}

